import moment from "moment";
import { DeviceEventEmitter, NativeModules } from "react-native";
import XLog from "./XLog";
const { AlarmLibraryModule } = NativeModules;

class AlarmStrategy {
    constructor(clientRef, strategy) {
        this.clientRef = clientRef;
        this.strategyContent = strategy;
        this.eventHandler = null;
        this.alarmIds= [];
        this.dispatchEvent = function(data) {
            this.eventHandler && this.eventHandler(data);
		}
    }

    on(callback) {
		this.eventHandler = callback;
	}

    async setAlarms() {
        let times = JSON.parse(this.strategyContent);
        for(let content of times) {
            let alarmTime = moment(content.time, "HH:mm");
            let id = await AlarmLibraryModule.setAlarm(1, alarmTime.hour(), alarmTime.minute(), 
                0, JSON.stringify(content), ""+content.light, this.clientRef);
            this.alarmIds.push(id);
        }
    }

    async cancelAlarm() {
        try{
            for(let id of this.alarmIds) {
                await AlarmLibraryModule.cancelAlarm(id);
            }
        }catch(error) {
            XLog.e("cancel alarm:",error);
        }
    }
}

export default class AlarmStrategyManager {
    static alarms = {};
    static eventHandler = null;
    static dispatchEvents(data) {
        console.log("data:",data);
		let clientRef = data && data.clientRef;
        if(this.alarms[clientRef]) {
            this.alarms[clientRef].dispatchEvent(data);
        }
	}

    static setEventHandler() {
		this.eventHandler = DeviceEventEmitter.addListener("alarm_event", (data) => this.dispatchEvents(data));
	}

    static async createAlarmStrategy(settings) {
        let clientRef = Math.floor((Math.random()*100)+1) + "_" + Date.now();
		let alarm = new AlarmStrategy(clientRef, settings);
        await alarm.setAlarms();

		/* Listen alarm event */
		if(this.eventHandler === null) {
			this.setEventHandler();
		}
		this.alarms[clientRef] = alarm;

		return alarm;
	}

    static async removeAlarmStrategy(alarm) {
        if(alarm) {
            await alarm.cancelAlarm();
            delete this.alarms[alarm.clientRef];
            if(Object.keys(this.alarms).length > 0) {
                if (this.eventHandler !== null) {
                    this.eventHandler.remove();
                    this.setEventHandler();
                }
            }
        }
    }
}